package edu.zjut.hjg.saas.common.support.spring;

import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.web.bind.support.WebArgumentResolver;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter;
import org.springframework.web.servlet.mvc.annotation.ModelAndViewResolver;

/**
 * 扩展spring默认的DispatcherServlet
 * 
 * @author hjg
 */
public class ExtendDispatcherServlet extends DispatcherServlet {

    private static final long serialVersionUID = 3555474592751619165L;

    @Override
    protected WebApplicationContext initWebApplicationContext() {
        // 自动装配用户自定义的WebArgumentResolver和ModelAndViewResolver
        WebApplicationContext wac = super.initWebApplicationContext();
        try {
            AnnotationMethodHandlerAdapter handler = wac
                    .getBean(AnnotationMethodHandlerAdapter.class);
            // 用户自定义的WebArgumentResolver
            Map<String, WebArgumentResolver> argsMap = wac
                    .getBeansOfType(WebArgumentResolver.class);
            int argSize = argsMap.size();
            WebArgumentResolver[] argResolvers = new WebArgumentResolver[argSize];
            argsMap.values().toArray(argResolvers);

            // 用户自定义的ModelAndViewResolver
            Map<String, ModelAndViewResolver> mavsMap = wac
                    .getBeansOfType(ModelAndViewResolver.class);
            int mavSize = mavsMap.size();
            ModelAndViewResolver[] mavResolvers = new ModelAndViewResolver[mavSize];
            mavsMap.values().toArray(mavResolvers);
            // 装配
            handler.setCustomArgumentResolvers(argResolvers);
            handler.setCustomModelAndViewResolvers(mavResolvers);
        } catch (BeansException e) {
            return wac;
        }
        return wac;
    }
}
